package com.ziyun.erp.modules.facilitator.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.service.common.constant.AppType;
import com.service.common.model.UserInfo;
import com.service.ucenter.api.UserLoginService;
import com.service.ucenter.constant.UcenterResult;
import com.service.ucenter.model.login.RegisterParamDto;
import com.ziyun.erp.common.utils.MD5;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.facilitator.dao.FacilitatorDao;
import com.ziyun.erp.modules.facilitator.entity.*;
import com.ziyun.erp.modules.facilitator.service.FacilitatorSellerRelationService;
import com.ziyun.erp.modules.facilitator.service.FacilitatorService;
import com.ziyun.erp.modules.member.entity.UserBaseInfoEntity;
import com.ziyun.erp.modules.member.entity.UserLoginAccountEntity;
import com.ziyun.erp.modules.member.service.UserBaseInfoService;
import com.ziyun.erp.modules.member.service.UserLoginAccountService;
import com.ziyun.erp.modules.supp.service.SellerInfoService;
import com.ziyun.erp.modules.userTeam.entity.UserDistributionEntity;
import com.ziyun.erp.modules.userTeam.service.UserDistributionService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("facilitatorService")
public class FacilitatorServiceImpl extends ServiceImpl<FacilitatorDao, FacilitatorEntity> implements FacilitatorService {
    @Autowired
    private SellerInfoService sellerInfoService;
    @Autowired
    private UserLoginAccountService userLoginAccountService;
    @Autowired
    private UserLoginService userLoginServicel;
    @Autowired
    private UserDistributionService userDistributionService; //分销表
    @Autowired
    private FacilitatorSellerRelationService facilitatorSellerRelationService; //关系表
    @Autowired
    private UserBaseInfoService userBaseInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<FacilitatorEntity> page = new Page<>();
        page.setCurrent(Integer.valueOf(params.get("page").toString()));
        page.setSize(Integer.valueOf(params.get("limit").toString()));
        List<FacilitatorEntity> list = this.baseMapper.list(page, params);
        for (FacilitatorEntity facilitatorEntity : list) {
            if (StringUtils.isNotBlank(facilitatorEntity.getIdCardUrls())) {
                String[] imgs = facilitatorEntity.getIdCardUrls().split(",");
                facilitatorEntity.setImga(imgs[0]);
                facilitatorEntity.setImgb(imgs[1]);
            }
        }
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    public List<Map<String, Object>> getShops(String area) {
        return sellerInfoService.getShops(area);
    }

    //修改
    @Override
    @Transactional
    public R updateFacilitatorEntity(FacilitatorEntity facilitator) {
        this.baseMapper.updateById(facilitator);
        if (StringUtils.isNotBlank(facilitator.getNickname())){
            UserBaseInfoEntity userBaseInfoEntity = new UserBaseInfoEntity();
            userBaseInfoEntity.setUserId(facilitator.getUserId());
            userBaseInfoEntity.setNickname(facilitator.getNickname());
            userBaseInfoService.updateById(userBaseInfoEntity);
        }

        //如果重新导入了代理商信息,则进行更新
        String str = insertUserDistribution(facilitator);
        if (!"success".equals(str)) {
            return R.error(str);
        }

        //如果重新导入/添加了商户信息,则进行更新
        String res = insertFacilitatorSellerRelation(facilitator);
        if (!"success".equals(res)) {
            return R.error(res);
        }

        return R.ok();
    }

    @Override
    public FacilitatorEntity getFacilitatorEntity(Integer teamId) {
        return this.baseMapper.getFacilitatorEntity(teamId);
    }

    //新增
    @Override
    @Transactional
    public R saveFacilitatorEntity(FacilitatorEntity facilitator) {
        //判断手机号码是否已经注册
        UserLoginAccountEntity entity = userLoginAccountService.selectOne(new EntityWrapper<UserLoginAccountEntity>().eq("login_type", "mobile").eq("login_account", facilitator.getMobile()));
        if (entity != null) {
            //查询服务商表是否有该用户的信息
            List<FacilitatorEntity> facilitatorEntities = this.baseMapper.selectList(new EntityWrapper<FacilitatorEntity>().eq("user_id", entity.getUserId()).eq("source_type", "facilitator").eq("audit_status", 1).eq("del_flag", 0));
            if (facilitatorEntities.size() > 0) {
                return R.error("手机号码已经注册!");
            }
            //设置userId
            facilitator.setUserId(facilitatorEntities.get(0).getUserId());
        }else {
            //没有注册,则通过手机号码等信息进行注册
            //组装参数
            RegisterParamDto registerParamDto = new RegisterParamDto();
            registerParamDto.setUserType(0);
            registerParamDto.setAccount(facilitator.getTeamName());
            registerParamDto.setPhone(facilitator.getMobile());
            registerParamDto.setPassword(MD5.getMD5Code("000000"));
            registerParamDto.setRegisterSource("erp");
            //调用注册接口
            UcenterResult<UserInfo> result = userLoginServicel.registerByErp(AppType.erp, registerParamDto);
            if (result == null || result.getCode() != UcenterResult.success().getCode()) {
                return R.error(result.getMessage());
            }
            UserInfo userInfo = result.getData();
            facilitator.setUserId(userInfo.getUserId().intValue());
        }

        facilitator.setSourceType("facilitator");
        facilitator.setAuditStatus(1);
        this.baseMapper.insert(facilitator);
        //如果传入了联系人则更新
        if (StringUtils.isNotBlank(facilitator.getNickname())){
            UserBaseInfoEntity userBaseInfoEntity = new UserBaseInfoEntity();
            userBaseInfoEntity.setUserId(facilitator.getUserId());
            userBaseInfoEntity.setNickname(facilitator.getNickname());
            userBaseInfoService.updateById(userBaseInfoEntity);
        }
        //同时在分销表插入一条数据,角色为团长
        UserDistributionEntity userDistributionEntity = new UserDistributionEntity();
        userDistributionEntity.setUserId(facilitator.getUserId());
        userDistributionEntity.setTeamId(facilitator.getTeamId());
        userDistributionEntity.setRoleId(1);
        userDistributionEntity.setApplyType("added");
        userDistributionEntity.setSourceType("facilitator");
        userDistributionService.insert(userDistributionEntity);

        //插入代理商数据
        String str = insertUserDistribution(facilitator);
        if (!"success".equals(str)) {
            return R.error(str);
        }

        //插入商户数据
        String res = insertFacilitatorSellerRelation(facilitator);
        if (!"success".equals(res)) {
            return R.error(res);
        }

        return R.ok();
    }

    @Override
    @Transactional
    public R deleteFacilitatorEntity(List<FacilitatorEntity> facilitatorEntityList) {
        //解除服务商与代理商的关系,解除服务商与商户的关系
        for (FacilitatorEntity facilitatorEntity : facilitatorEntityList) {
            //将user_team表服务商置为删除
            facilitatorEntity.setDelFlag(1);
            this.updateBatchById(facilitatorEntityList);

            //解除分销表服务商与代理商的关系(将服务商和代理商的apply_type设置为已退出)
            //查询该团队下面的代理商,设置为已退出
            List<UserDistributionEntity> entityList = userDistributionService.selectList(new EntityWrapper<UserDistributionEntity>().eq("team_id", facilitatorEntity.getTeamId()));
            if (entityList.size() > 0) {
                for (UserDistributionEntity userDistribution : entityList) {
                    userDistribution.setApplyType("leave");
                }
                userDistributionService.updateBatchById(entityList);
            }

            //解除服务商与商户对应关系(将disabled设置失效)
            //查询该服务商下面的商户,设置为失效
            List<FacilitatorSellerRelationEntity> relationList = facilitatorSellerRelationService.selectList(new EntityWrapper<FacilitatorSellerRelationEntity>().eq("parent_user_id", facilitatorEntity.getUserId()));
            if (relationList.size() > 0) {
                for (FacilitatorSellerRelationEntity relation : relationList) {
                    relation.setDisabled(true);
                }
                facilitatorSellerRelationService.updateBatchById(relationList);
            }
        }
        return R.ok();
    }

    @Override
    public R chenckShop(Integer userId) {
        //查询省市区
        List<String> areaList = this.baseMapper.getareasByUserId(userId);
        //查询该服务商的商户
        List<String> shopList = this.baseMapper.getShopsByUserId(userId);
        //查询待审核的列表信息
        Map<String, Object> params=new HashMap<>();
        params.put("userId",userId);
        List<AuditVo> auditVoList = this.baseMapper.getAuditVo(params);
        return R.ok().put("areaList",areaList).put("shopList",StringUtils.join(shopList, ",")).put("auditVoList",auditVoList);
    }

    @Override
    public R refuse(Integer id,Integer flag) {
        FacilitatorSellerRelationEntity facilitatorSellerRelationEntity = facilitatorSellerRelationService.selectById(id);
        if (flag == 1) {
            facilitatorSellerRelationEntity.setAuditStatus(1);
        }else {
            facilitatorSellerRelationEntity.setAuditStatus(0);
        }
        facilitatorSellerRelationService.updateById(facilitatorSellerRelationEntity);
        return R.ok();
    }

    @Override
    public R searchQ(Map<String, Object> params) {
        //查询待审核的列表信息
        List<AuditVo> auditVoList = this.baseMapper.getAuditVo(params);
        return R.ok().put("auditVoList",auditVoList);
    }

    @Override
    public R facilitatorData(Map<String, Object> params) {
        List<FacilitatorVo> facilitatorVos = this.baseMapper.facilitatorData(params);
        Integer totalSeller = facilitatorVos.stream().map(FacilitatorVo::getSellerNum).reduce(0, Integer::sum);
        Integer totalActivate = facilitatorVos.stream().map(FacilitatorVo::getActivateNum).reduce(0, Integer::sum);
        BigDecimal totalTransaction = facilitatorVos.stream().map(FacilitatorVo::getTransactionAmount).reduce(new BigDecimal("0"), BigDecimal::add);
        BigDecimal totalPurchase = facilitatorVos.stream().map(FacilitatorVo::getPurchaseAccount).reduce(new BigDecimal("0"), BigDecimal::add);

        //服务商facilitatorList
        List<Map<String, Object>> facilitatorList = this.baseMapper.facilitatorList();
        return R.ok().put("facilitatorVos",facilitatorVos).put("totalSeller",totalSeller).put("totalActivate",totalActivate)
                .put("totalTransaction",totalTransaction).put("totalPurchase",totalPurchase).put("facilitatorList",facilitatorList);
    }

    @Override
    public R userDistributionList(Integer teamId) {
        List<Map<String, Object>> userDistributionList = this.baseMapper.userDistributionList(teamId);
        return R.ok().put("userDistributionList",userDistributionList);
    }

    @Override
    public R facilitatorStatisticVo(Map<String, Object> params) {
        Page<FacilitatorStatisticVo> page = new Page<>();
        page.setCurrent(Integer.valueOf(params.get("page").toString()));
        page.setSize(Integer.valueOf(params.get("limit").toString()));
        List<FacilitatorStatisticVo> list = this.baseMapper.facilitatorStatisticVo(page, params);
        page.setRecords(list);

        List<FacilitatorStatisticVo> listF = this.baseMapper.facilitatorStatisticVo(params);
        //商家数
        Integer sellerCount = listF.size();
        //激活数
        List<FacilitatorStatisticVo> activeList = listF.stream().filter(v -> "激活".equals(v.getStatus())).collect(Collectors.toList());
        Integer activeCount = activeList.size();
        //交易金额
        BigDecimal transactionAmount = listF.stream().map(FacilitatorStatisticVo::getTransactionAmount).reduce(new BigDecimal("0"), BigDecimal::add);
        //采购金额
        BigDecimal purchaseAccount = listF.stream().map(FacilitatorStatisticVo::getPurchaseAccount).reduce(new BigDecimal("0"), BigDecimal::add);
        //服务商数
        Integer facilitatorCount = listF.stream().map(FacilitatorStatisticVo::getFacilitatorName).collect(Collectors.toSet()).size();
        //代理人数
        Integer userDistributionCount = listF.stream().map(FacilitatorStatisticVo::getUserDistributionName).collect(Collectors.toSet()).size();
        return R.ok().put("page",new PageUtils(page)).put("sellerCount",sellerCount).put("activeCount",activeCount).put("transactionAmount",transactionAmount)
                .put("purchaseAccount",purchaseAccount).put("facilitatorCount",facilitatorCount).put("userDistributionCount",userDistributionCount);
    }

    //插入代理商数据
    private String insertUserDistribution(FacilitatorEntity facilitator) {
        if (StringUtils.isNotBlank(facilitator.getPhones())){
            String phones = facilitator.getPhones();
            String[] phoneList = phones.split(",");
            // 1个代理商只能对应1个服务商
            List<String> phoneL = userDistributionService.checkUserDistribution(phoneList);
            if (phoneL.size() > 0) {
                return "一个代理商只能对应一个服务商("+StringUtils.join(phoneL,",")+")";
            }

            //更新分销表
            userDistributionService.leaveTeam(facilitator.getTeamId());
            //判断手机号码是否已经注册
            for (String phone : phoneList) {
                //组装分销表实体
                UserDistributionEntity userDistribution =new UserDistributionEntity();
                userDistribution.setTeamId(facilitator.getTeamId());
                userDistribution.setRoleId(2);
                userDistribution.setApplyType("added");
                userDistribution.setSourceType("facilitator");

                //设置userID,没有注册的先注册了取,注册了的直接取
                UserLoginAccountEntity entity = userLoginAccountService.selectOne(new EntityWrapper<UserLoginAccountEntity>().eq("login_type", "mobile").eq("login_account", phone));
                //如果代理商的手机号码未注册,则进行注册
                if (entity == null) {
                    //组装参数
                    RegisterParamDto registerParamDto = new RegisterParamDto();
                    registerParamDto.setUserType(0);
                    registerParamDto.setPhone(phone);
                    registerParamDto.setPassword(MD5.getMD5Code("000000")); //新用户默认密码6个0
                    registerParamDto.setRegisterSource("erp");
                    //调用注册接口
                    UcenterResult<UserInfo> result = userLoginServicel.mobileRregisterByErp(AppType.erp, registerParamDto);
                    if (result == null || result.getCode() != UcenterResult.success().getCode()) {
                        return result.getMessage();
                    }
                    UserInfo userInfo = result.getData();
                    //插入到分销表
                    userDistribution.setUserId(userInfo.getUserId().intValue());
                }else {
                    //已经注册
                    userDistribution.setUserId(entity.getUserId());
                }
                //插入到分销表
                userDistributionService.insert(userDistribution);
            }
        }
        return "success";
    }

    //插入商户数据
    private String insertFacilitatorSellerRelation(FacilitatorEntity facilitator) {
        if (StringUtils.isNotBlank(facilitator.getSellerIds())) {
            String[] sellerIdList = facilitator.getSellerIds().split(",");
            // 1个商户只能对应1个代理商
            boolean flag=true;
            FacilitatorSellerRelationEntity foo=null;
            for (String sellerId : sellerIdList) {
                FacilitatorSellerRelationEntity entity = facilitatorSellerRelationService.selectOne(new EntityWrapper<FacilitatorSellerRelationEntity>().eq("seller_id", sellerId).eq("audit_status", 1).eq("disabled", 0));
                if (entity != null) {
                    flag=false;
                    foo=entity;
                    break;
                }
            }
            if (!flag){
                return "商户ID"+foo.getSellerId()+"已绑定一个代理商";
            }
            facilitatorSellerRelationService.updateDisabled(facilitator.getUserId());
            //更新服务商与商户对应关系表
            for (String sellerId : sellerIdList) {
                FacilitatorSellerRelationEntity entity = new FacilitatorSellerRelationEntity();
                entity.setParentUserId(facilitator.getUserId());
                entity.setSellerId(Integer.valueOf(sellerId));
                entity.setAuditStatus(1);
                entity.setCreateName(UserUtils.getCurentUser().getUsername());
                facilitatorSellerRelationService.insert(entity);
            }
        }
        return "success";
    }
}
